

#include <memory.h>
#include <video.h>
#include <klib.h>


struct __page *__page_table;
unsigned int   __pages;
char           __pt_generated = 0;
struct __page *__last_mpage = NULL;
struct __page *__last_fpage = NULL;

/*
 * This is the freeGSD kernel's implementation of malloc.
 * Absolutely essential but has flaws. Allocats memory in a
 * fairly static manor from RAM.
 */

void *__do_malloc(unsigned int size){

  if (!__pt_generated) return NULL; /* If the page table has not been */
                                    /* generated then return NULL.    */
  /* Search for a table with memory open. */

  /* __last_fpage points to the last page with free()'d mem.         */
  if (__last_fpage != NULL){
    
  }

  /* __last_mpage points to the last page used for malloc()'ing mem. */
  if (__last_mpage != NULL){
    
  }

  

}

int __do_free(void *ptr){



}

/*
 * This is an important function. This function initializes the memory
 * used by the system. This is has some flaws, right now the memory to
 * use must be specified at compile time.
 */

void __init_memory(){

  /* Print some info... */
  char mem_size[10];
  char page_size[10];
  itos(__MEMORY_SIZE, mem_size, 10);
  itos(__PAGE_SIZE, page_size, 10);

  k_print("  Memory size (MB):   ");
  k_print(mem_size);
  k_printl();

  k_print("  Page size (bytes):  ");
  k_print(page_size);
  k_printl();

  __page_table = (struct __page *) __PAGE_TABLE_START;
  
  /* The basic idea is this: start at the top of the memory   */
  /* and work our way down until the page table hits the next */
  /* page being made. Then we are done.                       */

  k_print(" Generating page table at 0x400000...\n");

  int cur_page_loc = (__MEMORY_SIZE - 1) * __MEGABYTE;
  int cur_table_loc = 0;
  int cur_table_ptr = __PAGE_TABLE_START;

  while (1){

    cur_page_loc -= __PAGE_SIZE;
    
    if ( cur_page_loc < (cur_table_ptr + sizeof(struct __page))){
      /* We are finished generating the page table. */
      break;
    }

    __page_table[cur_table_loc].offset = cur_page_loc;
    __page_table[cur_table_loc].flags = 0;
    cur_table_loc++;
    cur_table_ptr += sizeof(struct __page);

  }
  __pages = cur_table_loc;

  k_print(" Page table generated.\n");

  /* Give the info for the page table generated. */

  k_print("  Pages:              ");
  char buf[13];
  itos(__pages, buf, 13);
  k_print(buf);
  k_printl();

  char pt_size[10];
  itos(__pages * sizeof(struct __page), pt_size, 10);
  k_print("  Page table size:    ");
  k_print(pt_size);
  k_printl();
  
  char alloc[13];
  itos(__pages * __PAGE_SIZE, alloc, 13);
  k_print("  Allocatable memory: ");
  k_print(alloc);
  k_printl();

  __pt_generated = 1;
  
}
